package com.example.server.security.context;

import com.example.common.security.UserDetails;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;


public class SessionBaesdSecurityContextHolder implements SecurityContextHolder {

    public static final String SESSION_USER_DETAILS_PARAM = "auth";

    @Override
    public UserDetails getUserDetails() {
        ServletRequestAttributes
                requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = requestAttributes.getRequest();
        UserDetails userDetails = (UserDetails) request.getSession().getAttribute(SESSION_USER_DETAILS_PARAM);
        return userDetails;
    }

    @Override
    public void setUserDetails(UserDetails userDetails) {

        ServletRequestAttributes
                requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = requestAttributes.getRequest();
        request.getSession().setAttribute(SESSION_USER_DETAILS_PARAM, userDetails);
    }
}
